package com.swt.agy.backend.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

@Slf4j
public class HttpUtil {

    public static byte[] doGet(String httpUrl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        ByteArrayOutputStream baos = null;
        // 返回结果字符串
        byte[] result = null;
        byte[] buff = new byte[1024];
        int len = 0;
        try {
            // 创建远程url连接对象
            URL url = new URL(httpUrl);
            // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
            connection = (HttpURLConnection) url.openConnection();
            // 设置连接方式：get
            connection.setRequestMethod("GET");
            // 设置连接主机服务器的超时时间：5000毫秒
            connection.setConnectTimeout(10000);
            // 设置读取远程返回的数据时间：60000毫秒
            connection.setReadTimeout(60000);
            // 发送请求
            connection.connect();
            // 通过connection连接，获取输入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                baos = new ByteArrayOutputStream();
                while ((len = is.read(buff)) != -1) {
                    baos.write(buff, 0, len);
                }
                result = baos.toByteArray();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != baos) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return result;
    }

    public static String doGetString(String httpUrl) {
        String strResult = "";
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        try {
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5 * 1000);
            connection.connect();
            inputStream = connection.getInputStream();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int i;
            while ((i = inputStream.read()) != -1) {
                baos.write(i);
            }
            strResult = baos.toString();
            inputStream.close();
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                connection.disconnect();// 关闭远程连接
            }
        }
        return strResult;
    }

    /**
     * Post请求
     * @param postUrl
     * @param json
     * @return
     */
    public static String doPostString(String postUrl,String json) throws MalformedURLException {

        try {
            //1.通过在 URL 上调用 openConnection 方法创建连接对象
            URL url=new URL(postUrl);
            HttpURLConnection conn=(HttpURLConnection) url.openConnection();

            //2.处理设置参数和一般请求属性
            //2.1设置参数
            conn.setRequestMethod("POST");
            conn.setUseCaches(false);
            conn.setConnectTimeout(5 * 1000);

            //2.2请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");

            //2.3设置请求正文 提交数据
            if (!StringUtils.isEmpty(json)) {
                PrintWriter pw=new PrintWriter(new OutputStreamWriter(conn.getOutputStream()));
                pw.print(json);
                pw.flush();
                pw.close();
            }

            //3.使用 connect 方法建立到远程对象的实际连接。
            conn.connect();

            //4.远程对象变为可用。远程对象的头字段和内容变为可访问。
            //4.1获取HTTP 响应消息获取状态码
            if(conn.getResponseCode() == 200)
            {
                //4.2获取响应的头字段
                Map<String, List<String>> headers=conn.getHeaderFields();
                log.info("响应消息头：" + headers);

                //4.3获取响应正文
                BufferedReader reader = null;
                StringBuffer resultBuffer = new StringBuffer();
                String tempLine = null;

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                }
                reader.close();
                log.info("响应消息正文：" + resultBuffer.toString());
                return resultBuffer.toString();
            }
        } catch (MalformedURLException e) {
            log.error("url转换失败：" + postUrl, e);
            throw new MalformedURLException("url路径错误：" + postUrl);
        } catch (IOException e) {
            log.error("数据传输失败", e);
        }
        return "";
    }

}
